package com.huixin.zhang.common.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class LettuceCacheHandle {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @param key
     * @param val
     * @param timeOutSeconds
     */
    public void putByTimeLive(String key, String val, long timeOutSeconds) {
        if(StringUtils.isNotBlank(key) && val != null) {
            stringRedisTemplate.opsForValue().set(key, val, timeOutSeconds, TimeUnit.SECONDS);
        }
    }

    /**
     * @param key
     * @param val
     * @param timestamp
     */
    public void putByTimestamp(String key, String val, long timestamp) {
        if(StringUtils.isNotBlank(key) && val != null) {
            long difference = timestamp - System.currentTimeMillis();
            difference = difference - 5 * 1000;
            stringRedisTemplate.opsForValue().set(key, val, difference, TimeUnit.MILLISECONDS);
        }
    }

    /**
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return get(key, 0);
    }

    /**
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        if(StringUtils.isBlank(key))
            return false;
        return stringRedisTemplate.hasKey(key);
    }
    /**
     * @param key
     * @param timeOutSeconds
     * @return
     */
    public String get(String key, long timeOutSeconds) {
        if(StringUtils.isBlank(key))
            return null;
        if(!stringRedisTemplate.hasKey(key)) {
            return null;
        }
        if(timeOutSeconds > 0) {
            stringRedisTemplate.expire(key, timeOutSeconds, TimeUnit.SECONDS);
        }
        return stringRedisTemplate.opsForValue().get(key);
    }

    public boolean delete(String key) {
        if(hasKey(key)) {
            return stringRedisTemplate.delete(key);
        }
        return false;
    }
}
